/*
 * @lc app=leetcode.cn id=971 lang=typescript
 *
 * [971] 翻转二叉树以匹配先序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function flipMatchVoyage(root: TreeNode | null, voyage: number[]): number[] {
  const preorder = (root: TreeNode | null): boolean => {
    // 遍历到叶节点，无需交换
    if (root === null) return true;
    // 根节点的值不相同，无法匹配
    if (root.val !== voyage[idx]) {
      ans.length = 0;
      ans.push(-1);
      return false;
    }
    // 找到左子树的根节点
    idx++;
    // 左节点值不同，翻转节点
    if (root.left && root.left.val !== voyage[idx]) {
      const temp = root.left;
      root.left = root.right;
      root.right = temp;
      ans.push(root.val);
    }
    // 左右子树是否相同
    if (!preorder(root.left)) return false;
    if (!preorder(root.right)) return false;
    return true;
  };
  const ans: number[] = [];
  let idx = 0;
  preorder(root);
  return ans;
}
// @lc code=end
